package com.example.user.service.impl;

import com.example.common.dto.UserDto;
import com.example.shared.entity.EmailVerification;
import com.example.shared.entity.User;
import com.example.user.exception.UserExistedException;
import com.example.user.payload.EmailRegistrationPayload;
import com.example.shared.repository.EmailVerificationRepository;
import com.example.shared.repository.UserRepository;
import com.example.user.service.UserService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private EmailVerificationRepository emailVerificationRepository;
    @Autowired
    private ModelMapper modelMapper;

    @Override
    public UserDto findUserByName(String name) {
        User user = Optional.ofNullable(userRepository.findByName(name))
                .orElseThrow(() -> new RuntimeException(name + " not found"));
        return modelMapper.map(user, UserDto.class);
    }

    @Override
    public User registerWithEmail(EmailRegistrationPayload payload) {
        if (emailExists(payload.getEmail())) {
            throw new UserExistedException("存在账号已被该邮箱所注册: " + payload.getEmail());
        }

        final User user = Optional.ofNullable(modelMapper.map(payload, User.class)).orElseThrow(
                () -> new RuntimeException("convert error"));
        return userRepository.save(user);
    }

    @Override
    public EmailVerification createVerification(User user, String token) {
        EmailVerification verification = new EmailVerification(user, token);
        return emailVerificationRepository.save(verification);
    }

    @Override
    public EmailVerification getVerificationFromToken(String token) {
        return null;
    }

    @Override
    public void saveRegisteredUser(User user) {
        userRepository.save(user);
    }

    private boolean emailExists(String email) {
        return userRepository.findByEmail(email) != null;
    }
}